from django.contrib import messages
from django.contrib.auth import login, authenticate, logout, update_session_auth_hash
from django.contrib.auth.forms import UserCreationForm, PasswordChangeForm
from django.http import HttpResponse
from django.shortcuts import render, redirect

from .forms import UserLoginForm


# Create your views here.
# def my_register(request):
#     if request.method == 'POST':
#         form = UserCreationForm(request.POST)
#         if form.is_valid():
#             form.save()
#             messages.success(request, '注册成功！')
#             HttpResponse(request, "Created device successfully")
#     else:
#         form = UserCreationForm()
#     return render(request, 'userinfo_register.html', {'form': form})


def user_login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            if request.user.is_superuser:#判断是否为超级管理员
                print(request.POST.get('username'), request.user.is_superuser.numerator, request.user.is_authenticated)
                messages.success(request, '登录成功！')
                return redirect('device:device_list')
            else:
                logout(request)#没有权限注销登录
                messages.error(request, '您没有权限登录！')
                return redirect('user_manage:user_login')
        else:
            messages.error(request, '用户名或者密码错误')
            return redirect('user_manage:user_login')
    # else:
    #     messages.error(request, '您没有权限登录！')
    #     return redirect('user_manage:user_login')
    else:
        form = UserLoginForm()
        return render(request, 'userinfo_login.html', {'form': form})


# 注销登录
def user_logout(request):
    logout(request)
    return redirect('device:device_list')


# 更新密码
def user_password_change(request):
    if request.method == 'POST':
        form = PasswordChangeForm(data=request.POST,user=request.user.id)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, '密码修改成功！')
            return redirect('device:device_list')
        else:
            messages.success(request, '密码修改失败！')
            return redirect('user_manage:user_password_change')
    else:
        form = PasswordChangeForm(data=request.POST, user=request.user)
        return render(request, 'user_password_change.html', {'form': form})

def test(request):
    return render(request, 'test.html', {})
